package soccer.utility.db;



import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.MapListHandler;
public class dbUtility {
	  private static dbUtility dbInstance = null;
	  
	  public  static synchronized dbUtility getInstance(){
		  if(dbInstance == null){
			  dbInstance = new dbUtility();
		  }
		  return dbInstance;
	  }
	
	private List executeQueryMap(Connection conn ,String query, Object[] param){
		QueryRunner qrunner = new QueryRunner();
		List maplist = null;
		try {
			 maplist  = (List) qrunner.query(conn, query,param, new MapListHandler());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return maplist;
	}
    private List executeQueryMap(Connection conn,String query){
		QueryRunner  qrunner = new QueryRunner();
		List mapList = null;
		try{
			mapList = (List)qrunner.query(conn, query, new MapListHandler());
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		return mapList;
	}
	private  int updateQuery(Connection conn , String query ,Object[] params){
		int insertedrow = 0;
		QueryRunner qrunner = new QueryRunner();
		try {
			insertedrow = qrunner.update(conn, query,params);
		} catch (SQLException e) {
		
			e.printStackTrace();
		}
		return insertedrow;
	}
	private int updateQuery(Connection conn , String query){
		int insertedrow = 0;
		QueryRunner qrunner = new QueryRunner();
		try {
			insertedrow = qrunner.update(conn, query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return insertedrow;
	}
	
	public List execute(String query){
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection conn = cm.getConnection();	
	    List list =	executeQueryMap(conn, query);
	    cm.closeConnection(conn);
	    return list;
	   
	}
	public List execute(String query, Object[] param){
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection conn = cm.getConnection();	
	    List list =	executeQueryMap(conn, query,param);
	    cm.closeConnection(conn);
	    return list;
	}
	public int update (String query){
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection conn =  cm.getConnection();
		int rowId = updateQuery(conn, query);
		cm.closeConnection(conn);
		return rowId;
	}
	public int update (String query, Object[] params){
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection conn =  cm.getConnection();
		int rowId = updateQuery(conn, query,params);
		cm.closeConnection(conn);
		return rowId;
	}
}
